package com.codebo.homiematch.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codebo.homiematch.common.ErrorCode;
import com.codebo.homiematch.exception.ThrowUtils;
import com.codebo.homiematch.mapper.UserMapper;
import com.codebo.homiematch.model.dto.LoveRequest;
import com.codebo.homiematch.model.dto.UserListQueryRequest;
import com.codebo.homiematch.model.entity.User;
import com.codebo.homiematch.model.vo.UserVO;
import com.codebo.homiematch.service.HomeService;
import com.codebo.homiematch.service.UserService;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.Cacheable;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HomeServiceImpl implements HomeService
{
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;

    @Cacheable(value = "userListCache")
    @Override
    public Page<UserVO> getUserList(UserListQueryRequest userListQueryRequest)
    {
        int current = userListQueryRequest.getCurrent();
        int pageSize = userListQueryRequest.getPageSize();
        String sortField = userListQueryRequest.getSortField();
        String sortOrder = userListQueryRequest.getSortOrder();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderBy(sortField != null, !sortOrder.equals("descend"), sortField);

        Page<User> userPage = userService.page(new Page<>(current, pageSize), queryWrapper);

        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());

        List<UserVO> userVOList = userPage.getRecords().
                stream()
                .map(user -> userService.getUserVO(user))
                .collect(Collectors.toList());
        userVOPage.setRecords(userVOList);


        return userVOPage;
    }

    @Override
    public List<UserVO> love(LoveRequest loveRequest)
    {
        long id = loveRequest.getId();
        List<String> tags = loveRequest.getTags();
        ThrowUtils.throwIf(tags == null || tags.isEmpty(), ErrorCode.PARAMS_ERROR, "数据不能为空");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("id",id);
        for (String tag : tags)
        {
            queryWrapper.like("tags", tag).or();
        }
        List<User> users = userMapper.selectList(queryWrapper);
        List<UserVO> userVOList = users.stream().map(user -> userService.getUserVO(user)).collect(Collectors.toList());

        return userVOList;
    }

}
